import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:toast/toast.dart';
import '../config/api.dart';
//import 'package:shared_preferences/shared_preferences.dart';
class RegisterPage extends StatefulWidget {
  RegisterPage({Key key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}
  
class _RegisterPageState extends State<RegisterPage> {
  static bool isChinaPhoneLegal(String str) {
  return new RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$').hasMatch(str);
}
   FocusNode focusNode = FocusNode();
   Map user;
     @override
void initState() {
  super.initState();
  addtoken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlwiMTU4NjI2Mzc5OThcIiIsImlhdCI6MTU5Njc5ODE2MSwiZXhwIjoxNTk3NDAyOTYxfQ.SfjQJ8nl3TzOm4pUNCUOlIPGR566NAI-g8GYVj-VYYM');
   //添加listener监听
   //对应的TextField失去或者获取焦点都会回调此监听
    focusNode.addListener((){
      if (!focusNode.hasFocus) {
        print('得到焦点');
         if(this._password1.text!=this._password.text){
          _toastTow();
        }
      }else{
        if(this._password1.text!=this._password.text){
          _toastTow();
        }
      print('失去焦点');
      }
      if(this._password1.text!=this._password.text){
          _toastTow();
        }
    });
  
}
//是否已经注册
bool fo=false;
void getusere(v)async{
  getlogin(v).then((value) => {
   print(value.data['err_code']),
    if(value.data['err_code']==1){
      setState((){
        fo=true;
        print('可以注册${user}');
       getadduser(user);
      })
    }
  });
}
//发起注册请求
void getadduser(v)async{
 if(fo){
   print('没有希望了${v}');
    getAddUsers(v).then((value) => {
    print(value),
    if(value.data['err_code']==0){
      addtoken(value.data['jwt']),
      print(value.data['jwt']),
      _toastuser(),
      //Navigator.pushNamed(context, '/')
    }
  });
 }
}
//保存用户的token
// void addtoken(v)async{
//   SharedPreferences prefs=await SharedPreferences.getInstance();
//   prefs.setString('token', json.encode(v));
//   print(prefs.getString('token'));
// }
//页面销毁
@override
void dispose() {
  super.dispose();
  //释放
  focusNode.dispose();
}
  //提示
  _toast()async{
     Toast.show("此手机号已注册", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
  }
  //两次密码不一致
  _toastTow()async{
    Toast.show("两次密码输入不一致", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
  }
  //登录注册成功
  _toastuser()async{
     Toast.show("注册成功", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
  }
  //请完善注册资料
  _toastflag()async{
     Toast.show("请完善资料", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
  }
   TextEditingController _user = TextEditingController();
    var _password = new TextEditingController();
     TextEditingController _password1 = TextEditingController();
  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
       resizeToAvoidBottomPadding: false, 
     // appBar: AppBar(),
      body: GestureDetector(
         behavior: HitTestBehavior.translucent,
        onTap: (){
          print('我啊');
           FocusScope.of(context).requestFocus(FocusNode());
        },
        child:Container(
         // width: ScreenUtil().setWidth(750),
         // height: double.infinity,
         padding: EdgeInsets.all(5),
           decoration: BoxDecoration(
            image: DecorationImage(image:NetworkImage("http://dbyxs.xyz:3005/uploads/c2a59c464936f30a34109531d89a9a8f",),fit:BoxFit.cover)
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              //注册头部区域
              Container(
                height: ScreenUtil().setHeight(400),
                width: ScreenUtil().setWidth(750),
                padding: EdgeInsets.only(top:25),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    IconButton(icon: Icon(Icons.chevron_left,size: 38,color: Colors.white,), onPressed: (){Navigator.pop(context);}),
                    SizedBox(width:100,),
                    SizedBox(height: 20,),
                    Container(padding: EdgeInsets.only(top:15), child:Text('您好 请注册',style: TextStyle(fontSize: 18,color: Colors.white),))
                     //IconButton(icon: Icon(Icons.close,size: 38,color: Colors.white,), onPressed: (){Navigator.pop(context);})
                  ],
                ),
              ),
              TextField(
               controller: TextEditingController.fromValue(TextEditingValue(
                  // 设置内容
                  text: _user.text,
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: _user.text.length)))
                      ),
               obscureText: false,
              decoration: InputDecoration(
                prefixIcon: IconButton(icon: Icon(Icons.account_box), onPressed: null),
                 disabledBorder: InputBorder.none,
                focusColor: Colors.black26,
                focusedBorder: OutlineInputBorder( //选中时外边框颜色
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide( color: Colors.black26,),
                            ),
                 hintText: "手机号",
              ),
              onChanged: (v){
                print(v);
                _user.text=v;
              },
            ),
            SizedBox(height: 10,),
            //密码
            TextField(
               controller: TextEditingController.fromValue(TextEditingValue(
                  // 设置内容
                  text: _password.text,
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: _password.text.length)))
                      ),
               obscureText: true,
              decoration: InputDecoration(
                prefixIcon: IconButton(icon: Icon(Icons.next_week), onPressed: null),
                 disabledBorder: InputBorder.none,
                focusColor: Colors.black26,
                focusedBorder: OutlineInputBorder( //选中时外边框颜色
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide( color: Colors.black26,),
                            ),
                 hintText: "密码",
              ),
              onChanged: (val){
               // print(v);
                setState(() {
                 this. _password.text=val;
                });
               
              },
              onEditingComplete: (){
        print('onEditingComplete');
      },
            ),
             SizedBox(height: 10,),
            //再次时输入密码
            TextField(
               controller: TextEditingController.fromValue(TextEditingValue(
                  // 设置内容
                  text: _password1.text,
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: _password1.text.length)))
                      ),
               obscureText: true,
                 focusNode: focusNode,
              decoration: InputDecoration(
                prefixIcon: IconButton(icon: Icon(Icons.next_week), onPressed: null),
                 disabledBorder: InputBorder.none,
                focusColor: Colors.black26,
                focusedBorder: OutlineInputBorder( //选中时外边框颜色
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide( color: Colors.black26,),
                            ),
                 hintText: "再次输入密码",
              ),
              onChanged: (v){
                print(v);
                setState(() {
                  _password1.text=v;
                });
                if(this._password1.text!=this._password.text){
          _toastTow();
        }
              },
            ),
            SizedBox(height:10),
            //注册
             Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15)
              ),
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              width: ScreenUtil().setWidth(750),
              height: ScreenUtil().setHeight(80),
              child: RaisedButton(
                 shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(22.0))),
                color: Color(0xff25D1D1),
                onPressed: (){
                 // _toast();
                   print(_password.text!='');
                  
                   print(isChinaPhoneLegal(_user.text));
                   if(isChinaPhoneLegal(_user.text)&&_password.text.length>=6&&_password1.text.length>=6){
                    if(this._password.text==this._password1.text){
                       var l={"user":_user.text,"password":_password1.text};
                    // print(l);
                     getusere(_user.text);
                    setState(() {
                      user=l;
                    });
                    // getadduser(l);
                    }
                   }else {
                     _toastTow();
                     _toastflag();
                   }
                //  print('登录');
                },child:Center(child: Text('注 册',style: TextStyle(fontSize:16,color:Colors.white,fontWeight: FontWeight.w600),),)),
            ),
              //  Container(
              //    padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              //    child: 
              //  )
            ],
          ),
        ) ,
      )
      );
  }
}